package net.ithe.interceptor;


import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import net.ithe.utils.CurrentHolder;
import net.ithe.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取到请求路径
        //String requestURI = request.getRequestURI();
        //2.判断请求路径是否是登录请求则放行
//        if (requestURI.contains("/login")){//是否包含
//            log.info("登录请求,放行:{}",requestURI);
//            return true;
//        }
        //3.如果不是获取token
        String token = request.getHeader("token");
        //4.判断token是否为空，如果为空则重定向到登录页面
        if (token == null||token.isEmpty()) {
            log.info("请求头token为空,返回登录页面");
            response.setStatus(401);
            return false;
        }
        //5.如果token存在校验失败返回401
        try {
            Claims claims=JwtUtils.parseToken(token);
            Integer empID=Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empID);
        }catch (Exception e){
            log.info("token校验失败,返回401");
            response.setStatus(401);
            return false;
        }
        //6.如果token存在，则校验成功，放行
        log.info("请求头token校验成功,放行");
        //移除
        CurrentHolder.remove();
        return true;


    }
}
